import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import { DownOutlined, PlusOutlined } from '@ant-design/icons';
import { Input, Modal, InputNumber, Upload, Button, Icon, Select, Radio, Card, Col, Checkbox, DatePicker, Tabs,Switch,message,TimePicker,Drawer,Dropdown,Menu} from 'antd';
import { formatMessage } from 'umi-plugin-react/locale';
import { FormComponentProps } from '@ant-design/compatible/es/form';
import React, { useState, useRef } from 'react';
import ProTable, { ProColumns, ActionType } from '@ant-design/pro-table';
import { queryRule, updateRule, queryEmojiItemRule, removeEmojiItemRule,addEmojiItemRule, updateEmojiItemRule} from '../service';
import styles from '../style.less';
import { bdExec } from '@/helpers/RequestHelper';
import EmojiForm from './EmojiForm';
import DictoryForm from './DictoryForm';
import * as RequestHelper from '@/helpers/RequestHelper';

// 导入自定义组件1
import PreviewForm from '@/components/PreviewForm';
import * as BdHelper from '@/utils/BdHelper';
import * as DataHelper from '@/helpers/DataHelper';
import * as TsxHelper from '@/helpers/TsxHelper';
import moment from 'moment';

// 常量
const { TextArea } = Input;
const FormItem = Form.Item;
const { RangePicker } = DatePicker;
const { Option } = Select;
const { TabPane } = Tabs;

// 定义: 数据表单属性
interface DataFormProps extends FormComponentProps {
  // dataModalVisible: boolean;
  isUpdate: boolean
  dataFormValues: any
  common: any
}

/**
* 添加节点
* @param fields
*/
const handleAdd = async (fields: any) => {
  return RequestHelper.bdExec({
      fn: addEmojiItemRule,
      args: fields,
      successMsg: formatMessage({ id: 'app.base.store-success' }),
      failMsg: formatMessage({ id: 'app.base.api-exception' }),
  });
};

/**
* 更新节点
* @param fields
*/
const handleUpdate = async (fields: any) => {
  return RequestHelper.bdExec({
      fn: updateEmojiItemRule,
      args: fields,
      successMsg: formatMessage({ id: 'app.base.update-success' }),
      failMsg:  formatMessage({ id: 'app.base.api-exception' }),
  });
};

// @ts-ignore
/**
*  删除节点
*/
const handleRemove = async (selectedRows: any[]) => {
  if (!selectedRows) return true;
  const ids:any = selectedRows.map(row => row.id).toString();
  return RequestHelper.bdExec({
      fn: removeEmojiItemRule,
      args: {ids},
      successMsg: formatMessage({ id: 'app.base.destroy-success' }),
      failMsg:  formatMessage({ id: 'app.base.api-exception' }),
      hasLoading: false
  });
};

const handleUpdateItem = async (fields: any) => {
  return bdExec({fn: updateEmojiItemRule, args: fields, successMsg: '更新成功',failMsg: '更新失败请重试！'});
};



// 数据表单
const DataForm: React.FC<DataFormProps> = props => {
  // 组件属性
  const { form, common, isUpdate, dataFormValues } = props;

  // 图片状态
  const [picture, setPicture] = useState<any[]>([]);
  const [uploadChanged, setUploadChanged] = useState<boolean>(false);
  const [pictureAnonymity, setPictureAnonymity] = useState<any[]>([]);
  const [uploadAnonymityChanged, setUploadAnonymityChanged] = useState<boolean>(false);
  const [previewModelVisible, handlePreviewModalVisible] = useState<boolean>(false);
  const [previewImg, setPreviewImg] = useState('');
  const [apiState, setApiState] = useState<any>({common:{}});

  const [drawerVisible,setDrawerVisible] = useState<boolean>(false);
  const [emojiValue, setEmojiValue] = useState<any>({});
  const [itemIsUpdate, setItemIsUpdate] = useState<boolean>(false);
  const [dataModalVisible, handleDataModalVisible] = useState<boolean>(false);
  const [dictoryIsUpdate, setDictoryIsUpdate] = useState<boolean>(false);
  const [dictoryModalVisible, handleDictoryModalVisible] = useState<boolean>(false);

  const [parentId, setParentId] = useState<any>('');
  // 选中的记录
  const [rowKeys, setRowKeys] = useState<string[]|number[]>([]);

  const actionRef = useRef<ActionType>();
  const itemActionRef = useRef<ActionType>();

    // 列定义
    const columns: ProColumns<any>[] = [
        {
            title: '顺序',
            dataIndex: 'rank_num',
            width: 150,
        },
        {
          title: '是否启用',
          dataIndex: 'is_enable',
          render: (value, record) => (
            <Switch checked={record.is_enable} onChange={async () => {
              let s = await handleUpdateItem({id: record.id, is_enable: (!record.is_enable).toString()});
              s && actionRef.current?.reload();
            }} />
          )
        },
        {
          title: '小组名',
          dataIndex: 'name',
          hideInSearch: true,
        },
        {
            title: '表情数量',
            dataIndex: 'count',
            hideInSearch: true,
        },
        {
            title: formatMessage({ id: 'app.base.option' }),
            dataIndex: 'option',
            valueType: 'option',
            render: (_, record) => (
                <>
                <a
                    onClick={() => {
                      setParentId(record.id);
                      setDrawerVisible(true);
                      setEmojiValue(record);
                    }}
                >
                    管理
                </a>
                </>
            ),
        },
    ];

    const itemColumns: ProColumns<any>[] = [
      {
          title: '顺序',
          dataIndex: 'rank_num',
          hideInSearch: true,
      },
      {
        title: '是否启用',
        dataIndex: 'is_enable',
        hideInSearch: true,
        render: (value, record) => (
          <Switch checked={record.is_enable} onChange={async () => {
            let s = await handleUpdateItem({id: record.id, is_enable: (!record.is_enable).toString()});
            s && itemActionRef.current?.reload();
          }} />
        )
      },
      
      {
        title: '表情图片',
        dataIndex: 'image_file_url',
        hideInSearch: true,
        render: (value, record) => (
          <img src={record.image_file_url} width='130px' onClick={() => {
              setPreviewImg(record.image_file_url)
              handlePreviewModalVisible(true )
          }} />
        )
      },
      {
          title: '表情符号',
          dataIndex: 'code',
          hideInSearch: true,
      },
      {
          title: formatMessage({ id: 'app.base.option' }),
          dataIndex: 'option',
          valueType: 'option',
          render: (_, record) => (
              <>
              <a
                  onClick={() => {
                    handleDataModalVisible(true);
                    setEmojiValue(record);
                    setItemIsUpdate(true);
                  }}
              >
                  编辑
              </a>
              </>
          ),
      },
  ];

    //提交表单
    const okHandle = () => {
      form.validateFields((err, fieldsValue) => {
        if (err) return;
        // if(picture.length > 0){
        //   fieldsValue.file_id   = picture[0].file_id
        //   fieldsValue.file_url  = picture[0].file_url
        // }
        
        console.log("submit fields ", fieldsValue)
        // console.log(moment(fieldsValue.publish_limit_date[0]),moment(fieldsValue.publish_limit_date[1]))
        var submitValue = [
            {
              "alias_key": 'publish_setting',
              "item_type":'system',
              "dict_item_arr": [
                {
                  "alias_key": "publish_ask",
                  "item_value": fieldsValue.publish_ask,
                  'item_type':"checkbox",
                },
                {
                  "alias_key": "email_verify",
                  "item_value": fieldsValue.publish_ask.indexOf('email_verify') >-1 ? true:false,
                  'item_type':"checkbox",
                },
                {
                  "alias_key": "phone_verify",
                  "item_value": fieldsValue.publish_ask.indexOf('phone_verify') >-1 ? true:false,
                  'item_type':"checkbox",
                },
                {
                  "alias_key": "prove_verify",
                  "item_value": fieldsValue.publish_ask.indexOf('prove_verify') >-1 ? true:false,
                  'item_type':"checkbox",
                },
                {
                  "alias_key": "post_publish",
                  "item_value": fieldsValue.post_publish,
                  'item_type':"radio",
                },
                {
                  "alias_key": "publish_limit_content",
                  "item_value": fieldsValue.publish_limit_content,
                  'item_type':"checkbox",
                },
                {
                  "alias_key": "publish_limit_post",
                  "item_value": fieldsValue.publish_limit_content.indexOf('publish_limit_post')>-1?true:false,
                  'item_type':"checkbox",
                },
                {
                  "alias_key": "publish_limit_comment",
                  "item_value": fieldsValue.publish_limit_content.indexOf('publish_limit_comment')>-1?true:false,
                  'item_type':"checkbox",
                },
                {
                  "alias_key": "publish_limit_type",
                  "item_value": fieldsValue.publish_limit_type,
                  'item_type':"select",
                },
                {
                  "alias_key": "publish_limit_date_start",
                  "item_value": fieldsValue.publish_limit_type == '1' ? moment(fieldsValue.publish_limit_date[0]).format("YYYY-MM-DD") : '',
                  'item_type':"select",
                },
                {
                  "alias_key": "publish_limit_date_end",
                  "item_value": fieldsValue.publish_limit_type == '1' ? moment(fieldsValue.publish_limit_date[1]).format("YYYY-MM-DD") : '',
                  'item_type':"select",
                },
                {
                  "alias_key": "publish_limit_period_start",
                  "item_value": fieldsValue.publish_limit_type == '2' ? moment(fieldsValue.publish_limit_date[0]).format("YYYY-MM-DD HH:mm:ss") : '',
                  'item_type':"select",
                },
                {
                  "alias_key": "publish_limit_period_end",
                  "item_value": fieldsValue.publish_limit_type == '2' ? moment(fieldsValue.publish_limit_date[1]).format("YYYY-MM-DD HH:mm:ss") : '',
                  'item_type':"select",
                },
                {
                  "alias_key": "publish_limit_cycle_start",
                  "item_value": fieldsValue.publish_limit_type == '3' ? moment(fieldsValue.publish_limit_cycle_start).format("HH:mm:ss") : '',
                  'item_type':"select",
                },
                {
                  "alias_key": "publish_limit_cycle_end",
                  "item_value": fieldsValue.publish_limit_type == '3' ? moment(fieldsValue.publish_limit_cycle_end).format("HH:mm:ss") : '',
                  'item_type':"select",
                },
                {
                  "alias_key": "publish_limit_rule",
                  "item_value": fieldsValue.publish_limit_rule,
                  'item_type':"radio",
                },
                {
                  "alias_key": "publish_limit_prompt",
                  "item_value": fieldsValue.publish_limit_prompt,
                  'item_type':"text",
                },
                {
                  "alias_key": "post_edit",
                  "item_value": fieldsValue.post_edit,
                  'item_type':"radio",
                },
                {
                  "alias_key": "post_edit_timelimit",
                  "item_value": fieldsValue.post_edit_timelimit,
                  'item_type':"number",
                },
                {
                  "alias_key": "post_edit_sticky",
                  "item_value": fieldsValue.post_edit_sticky,
                  'item_type':"radio",
                },
                {
                  "alias_key": "post_edit_essence",
                  "item_value": fieldsValue.post_edit_essence,
                  'item_type':"radio",
                },
                {
                  "alias_key":'sns_number',
                  "item_value": fieldsValue.sns_number,
                  'item_type':"checkbox",
                },
                {
                  "alias_key": "editor_group_required",
                  "item_value": fieldsValue.editor_group_required || parseData('editor_group_required',dataFormValues),
                  'item_type':"radio",
                },
                {
                  "alias_key": "editor_title_view",
                  "item_value": fieldsValue.editor_title_view || parseData('editor_title_view',dataFormValues),
                  'item_type':"radio",
                },
                {
                  "alias_key": "editor_title_required",
                  "item_value": fieldsValue.editor_title_required || parseData('editor_title_required',dataFormValues),
                  'item_type':"radio",
                },
                {
                  "alias_key": "editor_title_word_count",
                  "item_value": fieldsValue.editor_title_word_count || parseData('editor_title_word_count',dataFormValues),
                  'item_type':"number",
                },
                {
                  "alias_key": "editor_post_word_count",
                  "item_value": fieldsValue.editor_post_word_count || parseData('editor_post_word_count',dataFormValues),
                  'item_type':"number",
                },
                {
                  "alias_key": "editor_comment_word_count",
                  "item_value": fieldsValue.editor_comment_word_count || parseData('editor_comment_word_count',dataFormValues),
                  'item_type':"number",
                },
                // {
                //   "alias_key": "wechat_miniprogram_vod_close",
                //   "item_value": fieldsValue.wechat_miniprogram_vod_close,
                //   'item_type':"checkbox",
                // },
                // {
                //   "alias_key": "wechat_miniprogram_vod_image",
                //   "item_value": picture.length > 0 ? picture[0].file_url : parseData('wechat_miniprogram_vod_image',dataFormValues),
                //   'item_type':"file",
                // },
                {
                  "alias_key": "map_service",
                  "item_value": fieldsValue.map_service  || parseData('map_service',dataFormValues),
                  'item_type':"select",
                },
                {
                  "alias_key": "map_key",
                  "item_value": fieldsValue.map_key || parseData('map_key',dataFormValues),
                  'item_type':"text",
                },
                {
                  "alias_key": "anonymous_avatar",
                  "item_value": pictureAnonymity.length > 0 ? pictureAnonymity[0].file_url : parseData('anonymous_avatar',dataFormValues),
                  'item_type':"file",
                },
                // {
                //   'alias_key': 'editor_text_count',
                //   "item_value": fieldsValue.editor_text_count || parseData('editor_text_count',dataFormValues),
                //   'item_type':"number",
                // }
              ]
            }
        ]
        console.log("submit submitValue ", submitValue)
        // 如果更新成功之后，重置表单
        updateRule({config_json: JSON.stringify(submitValue)}).then((res:any) => {
          console.log('handleSubmit then success is ', JSON.stringify(submitValue))
          if(res.code == 0){
            // form.resetFields()
            // setPicture([]);
            message.success('保存成功');
          }
        })
  
      });
    };

  // 表单提交
  const handleSubmitDataForm = (value:any) => {
    return new Promise((resolve, reject) => {
        let s = dictoryIsUpdate ? handleUpdate(value) : handleAdd(value);
        resolve(s);
    }).then( status => {
        console.log("handleSubmitDataForm status is ", status)
        if(status){
          handleDictoryModalVisible(false)
            // setIsUpdate(false)
            // setDataFormValues({})
            if (actionRef.current) {
                actionRef.current.reload();
            }
        }
        // 返回执行结果:boolean, 子组件接收此值来重置数据
        return status;
    })
}

  // 表单提交
  const handleItemSubmitDataForm = (value:any) => {
    return new Promise((resolve, reject) => {
        let s = itemIsUpdate ? handleUpdate(value) : handleAdd(value);
        resolve(s);
    }).then( status => {
        console.log("handleSubmitDataForm status is ", status)
        if(status){
            handleDataModalVisible(false)
            // setIsUpdate(false)
            // setDataFormValues({})
            if (itemActionRef.current) {
              itemActionRef.current.reload();
            }
        }
        // 返回执行结果:boolean, 子组件接收此值来重置数据
        return status;
    })
}

const getEmojiTableData = (params:any) => {
  return queryEmojiItemRule(params).then((res:any) => {
      // setApiState(res.data)
      return res.data.listData
  })
}

  // 设置上传文件值
  const setUploadFile = (fileList:any) => {
    setUploadChanged(true)
    let fileArr = DataHelper.getLastUploadFile(fileList)
    console.log("fileArr is ", fileArr)
    if(fileArr.length > 0){
      setPicture(fileArr)
      setPreviewImg(fileArr[0].file_url)
    }else if(fileArr.length === 0){
      console.log('set picture []')
      setPicture([])
    }
  }

    // 设置Anonymity上传文件值
    const setAnonymityUploadFile = (fileList:any) => {
      setUploadAnonymityChanged(true)
      let fileArr = DataHelper.getLastUploadFile(fileList)
      console.log("fileArr is ", fileArr)
      if(fileArr.length > 0){
        setPictureAnonymity(fileArr)
        setPreviewImg(fileArr[0].file_url)
      }else if(fileArr.length === 0){
        console.log('set picture []')
        setPictureAnonymity([])
      }
    }

    const getTableData = (params:any) => {
      return queryRule(params).then((res:any) => {
          setApiState(res.data)
          return res.data.listData
      })
    }

    const parseData = (key:any,options:any) => {
      // console.log(options);
      var name:any = "";
      if(Array.isArray(options) && options.length>0){
        options.map(item=>{
          if(item.alias_key == key){
            name = item?.item_value;
          }
        })
      }
      return name
    }

  // 初始化变量
  const token = BdHelper.getBdToken()

  // 编辑时初始化 picture
  const defaultPicture = DataHelper.buildFileByUrl(parseData('wechat_miniprogram_vod_image',dataFormValues))
  const defaultAnonymityPicture = DataHelper.buildFileByUrl(parseData('anonymous_avatar',dataFormValues))

  // 是否展示图片上传按钮
  const showUploadButton = DataHelper.showUploadBtn(isUpdate, picture, defaultPicture, uploadChanged)
  const showUploadAnonymityButton = DataHelper.showUploadBtn(isUpdate, pictureAnonymity, defaultAnonymityPicture, uploadAnonymityChanged)

  

  // 弹出框
  // @ts-ignore
  return <Card>
    {/* <Col span={15}>
      <div className={styles.module_title}>{'发表要求'}：</div>
    </Col> */}
    <Col span={15}>
      <FormItem labelCol={{ span: 5 }} wrapperCol={{ span: 15 }} label={'发表要求'} extra="设置用户必须满足所选条件才能发表内容">
        {form.getFieldDecorator('publish_ask', {
          initialValue: parseData('publish_ask',dataFormValues),
          // rules: [{ required: true, message: formatMessage({ id: 'app.base.please_input_min_1' }) , min: 1 }],
        })(<Checkbox.Group onChange={(list)=>{console.log(list)}}>
        <Checkbox value={'email_verify'}>已绑定邮箱</Checkbox>
        <Checkbox value={'phone_verify'}>已绑定手机号</Checkbox>
        <Checkbox value={'prove_verify'}>已实名认证</Checkbox>
      </Checkbox.Group>)}
      </FormItem>
    </Col>
    <Col span={15}>
      <FormItem labelCol={{ span: 5 }} wrapperCol={{ span: 15 }} label={'发表开放时间'} extra="规定可以发表内容的时间，时区以服务器时区为准">
        {form.getFieldDecorator('post_publish', {
          initialValue: parseData('post_publish',dataFormValues),
          // rules: [{ required: true, message: formatMessage({ id: 'app.base.please_input_min_1' }) , min: 1 }],
        })(<Radio.Group buttonStyle="solid">
        <Radio value={'全天'}>全天</Radio>
        <Radio value={'规定时间'}>规定时间</Radio>
        {/* {common.selectOption && TsxHelper.buildRadioOption(common.selectOption)} */}
      </Radio.Group>)}
      </FormItem>
    </Col>
    {
    form.getFieldValue('post_publish') == '规定时间' &&
    <>
      <Col span={15}>
        <FormItem labelCol={{ span: 5 }} wrapperCol={{ span: 15 }} label={'限制内容'}>
          {form.getFieldDecorator('publish_limit_content', {
            initialValue: parseData('publish_limit_content',dataFormValues),
            // rules: [{ required: true, message: formatMessage({ id: 'app.base.please_input_min_1' }) , min: 1 }],
          })(<Checkbox.Group onChange={(list)=>{console.log(list)}}>
                <Checkbox value="publish_limit_post">帖子</Checkbox>
                <Checkbox value="publish_limit_comment">评论</Checkbox>
            </Checkbox.Group>)}
        </FormItem>
      </Col>
      <Col span={15}>
        <FormItem labelCol={{ span: 5 }} wrapperCol={{ span: 15 }} label={'限制类型'}>
          {form.getFieldDecorator('publish_limit_type', {
            initialValue: parseData('publish_limit_type',dataFormValues),
            // rules: [{ required: true, message: formatMessage({ id: 'app.base.please_input_min_1' }) , min: 1 }],
          })(<Select placeholder={formatMessage({ id: 'app.base.please_select' })} size={'default'} style={{ width: '100%' }}>
            <Option value="1">指定日期全天限制</Option>
            <Option value="2">指定某个时间段限制</Option>
            <Option value="3">指定每天的某个时间段限制</Option>
        </Select>)}
        </FormItem>
      </Col>
      {form.getFieldValue('publish_limit_type') == '1' &&
        <Col span={15}>
          <FormItem labelCol={{ span: 5 }} wrapperCol={{ span: 15 }} label={'全天限制'}>
            {form.getFieldDecorator('publish_limit_date', {
              initialValue: [moment(parseData('publish_limit_date_start',dataFormValues)),moment(parseData('publish_limit_date_end',dataFormValues))],
            })(<RangePicker format="YYYY-MM-DD" onChange={(value, dateString)=>{console.log(value, dateString)}} size={'default'} style={{ width: '100%' }} >
          </RangePicker>)}
          </FormItem>
        </Col>
      }
      {form.getFieldValue('publish_limit_type') == '2' &&
        <Col span={15}>
          <FormItem labelCol={{ span: 5 }} wrapperCol={{ span: 15 }} label={'时间段限制'}>
            {form.getFieldDecorator('publish_limit_date', {
              initialValue: [moment(parseData('publish_limit_period_start',dataFormValues)),moment(parseData('publish_limit_period_end',dataFormValues))],
            })(<RangePicker showTime  format="YYYY-MM-DD HH:mm:ss" size={'default'} style={{ width: '100%' }} >
          </RangePicker>)}
          </FormItem>
        </Col>
      }
      {form.getFieldValue('publish_limit_type') == '3' &&
      <>
        <Col span={15}>
          <FormItem labelCol={{ span: 5 }} wrapperCol={{ span: 15 }} label={'开始时间'}>
            {form.getFieldDecorator('publish_limit_cycle_start', {
              initialValue: moment(parseData('publish_limit_cycle_start',dataFormValues)),
            })(<TimePicker  size={'default'} style={{ width: '100%' }} >
          </TimePicker>)}
          </FormItem>
        </Col>
        <Col span={15}>
          <FormItem labelCol={{ span: 5 }} wrapperCol={{ span: 15 }} label={'结束时间'}>
            {form.getFieldDecorator('publish_limit_cycle_end', {
              initialValue: moment(parseData('publish_limit_cycle_end',dataFormValues)),
            })(<TimePicker  size={'default'} style={{ width: '100%' }} >
          </TimePicker>)}
          </FormItem>
        </Col>
      </>
      }
      <Col span={15}>
      <FormItem labelCol={{ span: 5 }} wrapperCol={{ span: 15 }} label={'限制规则'}>
        {form.getFieldDecorator('publish_limit_rule', {
          initialValue: parseData('publish_limit_rule',dataFormValues),
          // rules: [{ required: true, message: formatMessage({ id: 'app.base.please_input_min_1' }) , min: 1 }],
        })(<Radio.Group buttonStyle="solid">
        <Radio value={'禁止发表'}>禁止发表</Radio>
        <Radio value={'可以发表，但是需要审核'}>可以发表，但是需要审核</Radio>
      </Radio.Group>)}
      </FormItem>
    </Col>
    <Col span={15}>
      <FormItem labelCol={{ span: 5 }} wrapperCol={{ span: 15 }} label={'限制提示'} >
        {form.getFieldDecorator('publish_limit_prompt', {
          initialValue: parseData('publish_limit_prompt',dataFormValues),
          // rules: [{ required: true, message: formatMessage({ id: 'app.base.please_input_min_1' }) , min: 1 }],
        })(<Input placeholder={formatMessage({ id: 'app.base.please_input' })}/>)}
      </FormItem>
    </Col>
    </>  
    }
    

    <Col span={15}>
      <FormItem labelCol={{ span: 5 }} wrapperCol={{ span: 15 }} label={'内容编辑权限'} extra="内容发表后是否可以编辑">
        {form.getFieldDecorator('post_edit', {
          initialValue: parseData('post_edit',dataFormValues),
          // rules: [{ required: true, message: formatMessage({ id: 'app.base.please_input_min_1' }) , min: 1 }],
        })(<Radio.Group buttonStyle="solid">
        <Radio value={false}>不可编辑</Radio>
        <Radio value={true}>可以编辑</Radio>
      </Radio.Group>)}
      </FormItem>
    </Col>
    {
      form.getFieldValue('post_edit') == true && <>
        <Col span={15}>
          <FormItem labelCol={{ span: 5 }} wrapperCol={{ span: 15 }} label={'多长时间内可以编辑'} >
            {form.getFieldDecorator('post_edit_timelimit', {
              initialValue: parseData('post_edit_timelimit',dataFormValues),
              // rules: [{ required: true, message: formatMessage({ id: 'app.base.please_input_min_1' }) , min: 1 }],
            })(<InputNumber formatter={value => `${value}分钟以内`} style={{width:'100%'}}/>)}
          </FormItem>
        </Col>
        <Col span={15}>
          <FormItem labelCol={{ span: 5 }} wrapperCol={{ span: 15 }} label={'内容置顶后编辑权限'}>
            {form.getFieldDecorator('post_edit_sticky', {
              initialValue: parseData('post_edit_sticky',dataFormValues),
              // rules: [{ required: true, message: formatMessage({ id: 'app.base.please_input_min_1' }) , min: 1 }],
            })(<Radio.Group buttonStyle="solid">
            <Radio value={false}>不可编辑</Radio>
            <Radio value={true}>可以编辑</Radio>
          </Radio.Group>)}
          </FormItem>
        </Col>
        <Col span={15}>
          <FormItem labelCol={{ span: 5 }} wrapperCol={{ span: 15 }} label={'内容加精后编辑权限'}>
            {form.getFieldDecorator('post_edit_essence', {
              initialValue: parseData('post_edit_essence',dataFormValues),
              // rules: [{ required: true, message: formatMessage({ id: 'app.base.please_input_min_1' }) , min: 1 }],
            })(<Radio.Group buttonStyle="solid">
            <Radio value={false}>不可编辑</Radio>
            <Radio value={true}>可以编辑</Radio>
          </Radio.Group>)}
          </FormItem>
        </Col>
      </>
    }

    <Col span={15}>
      <FormItem labelCol={{ span: 5 }} wrapperCol={{ span: 15 }} label={'编辑器功能'}>
        {form.getFieldDecorator('sns_number', {
          initialValue: parseData('sns_number',dataFormValues),
          // rules: [{ required: true, message: formatMessage({ id: 'app.base.please_input_min_1' }) , min: 1 }],
        })(<Checkbox.Group onChange={(list)=>{console.log(list)}}>
              <Checkbox value="editor_group">小组</Checkbox>
              <Checkbox value="editor_title">标题</Checkbox>
              <Checkbox value="editor_emoji">表情</Checkbox>
              <Checkbox value="editor_image">图片</Checkbox>
              <Checkbox value="editor_video">视频</Checkbox>
              <Checkbox value="editor_audio">音频</Checkbox>
              <Checkbox value="editor_doc">文件</Checkbox>
              <Checkbox value="editor_at">艾特</Checkbox>
              <Checkbox value="editor_hashtag">话题</Checkbox>
              <Checkbox value="editor_expand">扩展功能</Checkbox>
              <Checkbox value="editor_lbs">定位</Checkbox>
              <Checkbox value="editor_anonymous">匿名</Checkbox>
          </Checkbox.Group>)}
      </FormItem>
    </Col>

    <Col span={15}>
      <div className={styles.module_title}>{'编辑器功能配置'}：</div>
    </Col>
    <Col span={15}>
      <Tabs defaultActiveKey="1">
        <TabPane tab="小组配置" key="1">
          <Col span={15}>
            <FormItem labelCol={{ span: 5 }} wrapperCol={{ span: 15 }} label={'小组是否必选'} extra="发表帖子的时候，小组是否必须选择">
              {form.getFieldDecorator('editor_group_required', {
                initialValue: parseData('editor_group_required',dataFormValues),
                // rules: [{ required: true, message: formatMessage({ id: 'app.base.please_input_min_1' }) , min: 1 }],
              })(<Radio.Group buttonStyle="solid">
              <Radio value={false}>否</Radio>
              <Radio value={true}>是</Radio>
            </Radio.Group>)}
            </FormItem>
          </Col>
        </TabPane>
        <TabPane tab="标题配置" key="2">
          <Col span={15}>
            <FormItem labelCol={{ span: 5 }} wrapperCol={{ span: 15 }} label={'标题输入框显示'} extra="弱显示需用户在编辑器的「扩展功能」里选择后才会显示标题输入框">
              {form.getFieldDecorator('editor_title_view', {
                initialValue: parseData('editor_title_view',dataFormValues),
                // rules: [{ required: true, message: formatMessage({ id: 'app.base.please_input_min_1' }) , min: 1 }],
              })(<Radio.Group buttonStyle="solid">
              <Radio value={false}>弱显示</Radio>
              <Radio value={true}>强显示</Radio>
            </Radio.Group>)}
            </FormItem>
          </Col>
          <Col span={15}>
            <FormItem labelCol={{ span: 5 }} wrapperCol={{ span: 15 }} label={'标题是否必填'} extra="发表帖子的时候，标题是否必填">
              {form.getFieldDecorator('editor_title_required', {
                initialValue: parseData('editor_title_required',dataFormValues),
                // rules: [{ required: true, message: formatMessage({ id: 'app.base.please_input_min_1' }) , min: 1 }],
              })(<Radio.Group buttonStyle="solid">
              <Radio value={false}>否</Radio>
              <Radio value={true}>是</Radio>
            </Radio.Group>)}
            </FormItem>
          </Col>
          <Col span={15}>
            <FormItem labelCol={{ span: 5 }} wrapperCol={{ span: 15 }} label={'标题字数限制'} extra="标题字数不得超过设置数">
              {form.getFieldDecorator('editor_title_word_count', {
                initialValue:  parseData('editor_title_word_count',dataFormValues),
                // rules: [{ required: true, message: formatMessage({ id: 'app.base.please_input_min_1' }) , min: 1 }],
              })(<InputNumber style={{width:'100%'}} />)}
            </FormItem>
          </Col>
        </TabPane>
        <TabPane tab="正文配置" key="3">
          <Col span={15}>
            <FormItem labelCol={{ span: 5 }} wrapperCol={{ span: 15 }} label={'帖子字数限制'} extra="帖子内容字数不得超过设置数">
              {form.getFieldDecorator('editor_post_word_count', {
                initialValue: parseData('editor_post_word_count',dataFormValues),
                // rules: [{ required: true, message: formatMessage({ id: 'app.base.please_input_min_1' }) , min: 1 }],
              })(<InputNumber style={{width:'100%'}} />)}
            </FormItem>
          </Col>
          <Col span={15}>
            <FormItem labelCol={{ span: 5 }} wrapperCol={{ span: 15 }} label={'评论字数限制'} extra="评论内容字数不得超过设置数">
              {form.getFieldDecorator('editor_comment_word_count', {
                initialValue: parseData('editor_comment_word_count',dataFormValues),
                // rules: [{ required: true, message: formatMessage({ id: 'app.base.please_input_min_1' }) , min: 1 }],
              })(<InputNumber style={{width:'100%'}} />)}
            </FormItem>
          </Col>
        </TabPane>
        <TabPane tab="表情配置" key="4">
          <div className={styles.top_tip}>启用表情后将在编辑器的输入框有表情包列表，但是数据库原生支持 Emoji 表情符，所以不启用的情况下，用户也可以通过表情键盘输入 Emoji 表情。</div>
          <Col span={24}>
          <ProTable<any>
            headerTitle=""
            actionRef={actionRef}
            rowKey="key"
            search={false}
            toolBarRender={(action, { selectedRows }) => [
              selectedRows && selectedRows.length > 0 && (
                <Dropdown
                    overlay={
                      <Menu
                          onClick={async e => {
                              if (e.key === 'remove') {
                                  TsxHelper.showDeleteConfirm(
                                      'danger',
                                      handleRemove,
                                      selectedRows,
                                      () => {
                                          setRowKeys([]);
                                          action.reload();
                                      }
                                  )
                              }
                          }}
                          selectedKeys={[]}
                      >
                        <Menu.Item key="remove">
                            {formatMessage({ id: 'app.base.batch_delete' })}
                        </Menu.Item>
                      </Menu>
                    }
                >
                  <Button>
                      {formatMessage({ id: 'app.base.batch_option' })} <DownOutlined />
                  </Button>
                </Dropdown>
            ),
              // @ts-ignore
              <Button icon={<PlusOutlined />} type="primary" onClick={() => { handleDictoryModalVisible(true);}}>
                {formatMessage({ id: 'app.base.create' })}
              </Button>
          ]}
            request={params => getEmojiTableData(params)}
            columns={columns}
            rowSelection={{
              onChange: (selectedRowKeys, selectedRows) => {
                  setRowKeys(selectedRowKeys);
              },
              selectedRowKeys: rowKeys,
            }}
            />
          </Col>
        </TabPane>
        {/* <TabPane tab="音视频配置" key="5">
          <Col span={15}>
            <FormItem labelCol={{ span: 8 }} wrapperCol={{ span: 12 }} label={'微信小程序展示和播放'} extra="请务必确保您的小程序已有相应的音视频播放类目的权限">
              {form.getFieldDecorator('wechat_miniprogram_vod_close', {
                initialValue: parseData('wechat_miniprogram_vod_close',dataFormValues),
                valuePropName: 'checked',
                // rules: [{ required: true, message: formatMessage({ id: 'app.base.please_input_min_1' }) , min: 1 }],
              })(<Switch  />)}
            </FormItem>
          </Col>
          <Col span={15}>
            <FormItem labelCol={{ span: 8 }} wrapperCol={{ span: 12 }} label={'微信小程序禁用提示图'} extra="必须配置了存储设置中的图片设置">
              {form.getFieldDecorator('picture', {
                initialValue: defaultPicture,
                // rules: [{required: true, message: '请上传图片'}],
              })(
                <Upload
                  listType={'picture'}
                  className={'upload-list-inline'}
                  action="/api/admin/tweetfiles/upload"
                  defaultFileList={defaultPicture}
                  beforeUpload={(file) => {
                    console.log('before upload file type:', file.type)
                    // todo: 这里可以对上传文件类型做限制
                    return true;
                  }}
                  data={{ type: 'image' , table_key : 'wechat_miniprogram_vod_image'}}
                  onRemove={() => setPicture([])}
                  onChange={(changeObj) => setUploadFile(changeObj.fileList)}
                  onPreview={() => handlePreviewModalVisible(true)}
                  headers={{
                    Authorization: `Bearer ${token}`,
                  }}
                >
                  {
                    showUploadButton ? (
                      <Button>
                        <Icon type="upload"/> {formatMessage({ id: 'app.base.upload' })}
                      </Button>
                    ) : null
                  }
                </Upload>
              )}
            </FormItem>
          </Col>
        </TabPane> */}
        <TabPane tab="定位配置" key="6">
          <Col span={15}>
            <FormItem labelCol={{ span: 5 }} wrapperCol={{ span: 15 }} label={'服务商'} extra="应用市场可以安装更多服务商">
              {form.getFieldDecorator('map_service', {
                initialValue: parseData('map_service',dataFormValues),
                // rules: [{ required: true, message: formatMessage({ id: 'app.base.please_input_min_1' }) , min: 1 }],
              })(<Select placeholder={formatMessage({ id: 'app.base.please_select' })} size={'default'} style={{ width: '100%' }}>
              {common.mapOption  && TsxHelper.buildSelectOption(common.mapOption )}
            </Select>)}
            </FormItem>
          </Col>
          <Col span={15}>
            <FormItem labelCol={{ span: 5 }} wrapperCol={{ span: 15 }} label={'API Key'} extra="配置 Key 后，才可使用地图位置的 WebServiceAPI 服务">
              {form.getFieldDecorator('map_key', {
                initialValue: parseData('map_key',dataFormValues),
                // rules: [{ required: true, message: formatMessage({ id: 'app.base.please_input_min_1' }) , min: 1 }],
              })(<Input style={{width:"100%"}}/>)}
            </FormItem>
          </Col>
        </TabPane>
        <TabPane tab="匿名配置" key="7">
          <Col span={15}>
            <FormItem labelCol={{ span: 8 }} wrapperCol={{ span: 12 }} label={'匿名头像'} extra="开启匿名功能后，匿名用户的头像。必须配置了存储设置中的图片设置">
              {form.getFieldDecorator('picture_anonymity', {
                initialValue: defaultAnonymityPicture,
                // rules: [{required: true, message: '请上传图片'}],
              })(
                <Upload
                  listType={'picture'}
                  className={'upload-list-inline'}
                  action="/api/admin/tweetfiles/upload"
                  defaultFileList={defaultAnonymityPicture}
                  beforeUpload={(file) => {
                    console.log('before upload file type:', file.type)
                    // todo: 这里可以对上传文件类型做限制
                    return true;
                  }}
                  data={{ type: 'image'  , table_key :'anonymous_avatar'}}
                  onRemove={() => setPicture([])}
                  onChange={(changeObj) => setAnonymityUploadFile(changeObj.fileList)}
                  onPreview={() => handlePreviewModalVisible(true)}
                  headers={{
                    Authorization: `Bearer ${token}`,
                  }}
                >
                  {
                    showUploadAnonymityButton ? (
                      <Button>
                        <Icon type="upload"/> {formatMessage({ id: 'app.base.upload' })}
                      </Button>
                    ) : null
                  }
                </Upload>
              )}
            </FormItem>
          </Col>
        </TabPane>
      </Tabs>
    </Col>
    
    
    <Col span={15}>
      <div style={{display: 'flex',justifyContent:'center',marginTop:20,}}>
        <Button type="primary" style={{marginLeft:30}} onClick={()=>{okHandle()}}>保存</Button>
      </div>
    </Col>
    {
      previewModelVisible && (
        <PreviewForm
          previewModelVisible={previewModelVisible}
          onVisibleModel={handlePreviewModalVisible}
          previewImg={previewImg}
        />
      )
    }
    {dataModalVisible == true &&
      <EmojiForm
        dataModalVisible={dataModalVisible}
        isUpdate={itemIsUpdate}
        parentId={parentId}
        dataFormValues={emojiValue}
        common={apiState.common || {}}
        onSubmit={ async formValue => handleItemSubmitDataForm(formValue) }
        onCancel={() => handleDataModalVisible(false)}
      />
    }
    {dictoryModalVisible == true &&
      <DictoryForm
        dataModalVisible={dictoryModalVisible}
        isUpdate={false}
        dataFormValues={dataFormValues}
        common={apiState.common || {}}
        onSubmit={ async formValue => handleSubmitDataForm(formValue) }
        onCancel={() => handleDictoryModalVisible(false)}
      />
    }
    <Drawer
          // title={`字典: ${parentDictName}`}
          placement="right"
          width="39%"
          closable={false}
          onClose={() => {
            setDrawerVisible(false)
            // setItemModalVisible(false)
          }}
          visible={drawerVisible}
          className={styles.dbDrawer}
        >
          <ProTable<any>
            headerTitle={`表情管理`}
            actionRef={itemActionRef}
            rowKey="key"
            search={false}
            // pagination={false}
            toolBarRender={(action, { selectedRows }) => [
              <Button icon={'plus'} type="primary" 
                onClick={() => {
                  handleDataModalVisible(true)
                }}
              >
                新建
              </Button>
            ]}
            request={(params) => getEmojiTableData(params)}
            params={{
              parent_id: parentId
            }}
            columns={itemColumns}
          />
        </Drawer>
  </Card>;
};

export default Form.create<DataFormProps>()(DataForm);
